import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * 测试操作相关的键
 */
public class TestKey {
    private Jedis jedis;

    // 在测试任务运行前初始化连接
    @Before
    public void initJedis() {
        this.jedis = new Jedis("localhost", 6379);
        // 选择 1号 数据库
        jedis.select(1);
    }

    // 在测试任务运行结束后释放连接
    @After
    public void releaseJedis() {
        // 清空当前数据库
        jedis.flushDB();
        // 释放连接
        jedis.close();
    }

    // 测试 String 类型的操作
    @Test
    public void testString() {
        String userKey = "user:id";
        for (int i = 1; i <= 10; i++) {
            jedis.set(userKey + ":" + i, UUID.randomUUID().toString().replace("-", ""));
        }

        Set<String> keys = jedis.keys("*");
        for (String key : keys) {
            System.out.println(key + "=" + jedis.get(key));
        }
    }

    @Test
    public void testList() {
        jedis.lpush("name", "张三", "李四", "王五");
        jedis.rpush("name", "mike", "marry", "jack");
        List<String> name = jedis.lrange("name", 0, -1);
        for (String s : name) {
            System.out.println(s);
        }
    }

    @Test
    public void testHash() {
        jedis.hset("user", "id", "100");
        jedis.hset("user", "name", "张三");
        jedis.hset("user", "age", "20");
        jedis.hset("user", "address", "重庆市");
        System.out.println(jedis.hget("user", "id"));
        System.out.println(jedis.hget("user", "name"));
        System.out.println(jedis.hget("user", "age"));
        System.out.println(jedis.hget("user", "address"));
    }

    @Test
    public void testSet() {
        jedis.sadd("age", "1", "2", "3", "4", "4", "5", "5");
        System.out.println("集合元素数量 = " + jedis.scard("age"));
        Set<String> age = jedis.smembers("age");
        for (String s : age) {
            System.out.println(s);
        }
    }

    @Test
    public void testZSet() {
        jedis.zadd("grade", 100.0, "小明");
        jedis.zadd("grade", 88.0, "小明");
        jedis.zadd("grade", 99.0, "小红");
        jedis.zadd("grade", 66.0, "小花");
        jedis.zadd("grade", 77.0, "小江");
        System.out.println("有序集合元素数量 = " + jedis.zcard("grade"));
        Set<String> grade = jedis.zrangeByScore("grade", 0, 100);
        for (String s : grade) {
            System.out.println(s);
        }
    }
}
